#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
大乐透增量训练脚本
支持同时增量训练LSTM-CRF模型和增强版LSTM-CRF模型
"""

import os
import sys
import subprocess
from datetime import datetime

# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, '..', '..'))
sys.path.append(project_root)

def incremental_train_dlt_model():
    """增量训练大乐透模型"""
    print("[START] 开始增量训练大乐透模型")
    print("=" * 60)
    
    # 配置路径
    data_file = os.path.join(project_root, 'scripts', 'dlt', 'dlt_history.csv')
    model_path = os.path.join(project_root, 'scripts', 'dlt', 'dlt_model.pth')
    scaler_path = os.path.join(project_root, 'scripts', 'dlt', 'scaler_X.pkl')
    
    # 检查必要的文件是否存在
    if not os.path.exists(data_file):
        print(f"[ERROR] 历史数据文件不存在: {data_file}")
        print("请先运行主程序获取大乐透历史数据")
        return False
    
    print(f"[DATA] 数据文件: {data_file}")
    print(f"[MODEL] LSTM-CRF模型: {model_path}")
    print(f"[SCALER] 特征缩放器: {scaler_path}")
    
    # 增量训练LSTM-CRF模型
    try:
        print("[TRAIN] 开始增量训练大乐透LSTM-CRF模型...")
        
        # 使用当前目录下的 Python 解释器
        python_executable = sys.executable
        original_train_script = os.path.join(project_root, 'scripts', 'dlt', 'train_dlt_model.py')
        
        # 运行原始训练脚本进行增量训练
        process = subprocess.Popen(
            [python_executable, original_train_script],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding='utf-8',
            errors='replace'
        )
        
        for line in process.stdout:
            try:
                clean_line = line.strip()
                if clean_line:
                    clean_line = clean_line.encode('utf-8', errors='ignore').decode('utf-8')
                    print(clean_line)
            except Exception as e:
                print(f"日志处理警告: {str(e)}")
        
        process.wait()
        
        if process.returncode == 0:
            print("[SUCCESS] 大乐透LSTM-CRF模型增量训练完成")
        else:
            print(f"[ERROR] 大乐透LSTM-CRF模型增量训练失败，返回码：{process.returncode}")
            return False
            
    except Exception as e:
        print(f"[ERROR] 大乐透LSTM-CRF模型增量训练过程出错: {e}")
        import traceback
        print(traceback.format_exc())
        return False
    
    # 增量训练增强版LSTM-CRF模型
    try:
        print("[TRAIN] 开始增量训练大乐透增强版LSTM-CRF模型...")
        
        # 检查增强版训练脚本是否存在
        enhanced_train_script = os.path.join(project_root, 'scripts', 'dlt', 'train_enhanced_lstm_crf.py')
        if os.path.exists(enhanced_train_script):
            # 使用当前目录下的 Python 解释器
            python_executable = sys.executable
            
            # 运行增强版训练脚本进行增量训练
            process = subprocess.Popen(
                [python_executable, enhanced_train_script],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                encoding='utf-8',
                errors='replace'
            )
            
            for line in process.stdout:
                try:
                    clean_line = line.strip()
                    if clean_line:
                        clean_line = clean_line.encode('utf-8', errors='ignore').decode('utf-8')
                        print(clean_line)
                except Exception as e:
                    print(f"日志处理警告: {str(e)}")
            
            process.wait()
            
            if process.returncode == 0:
                print("[SUCCESS] 大乐透增强版LSTM-CRF模型增量训练完成")
            else:
                print(f"[ERROR] 大乐透增强版LSTM-CRF模型增量训练失败，返回码：{process.returncode}")
        else:
            print("[WARN] 大乐透增强版LSTM-CRF训练脚本不存在，跳过增量训练")
            
    except Exception as e:
        print(f"[ERROR] 大乐透增强版LSTM-CRF模型增量训练过程出错: {e}")
        import traceback
        print(traceback.format_exc())
    
    return True

def main():
    """主函数"""
    print("[TARGET] 大乐透增量训练程序")
    print(f"[TIME] 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    success = incremental_train_dlt_model()
    
    print()
    if success:
        print("[SUCCESS] 增量训练完成！")
    else:
        print("[FAIL] 增量训练失败！")
    
    print(f"[TIME] 结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

if __name__ == "__main__":
    main()